// add-item.js
Page({
    data: {
      currentUser: {}, // 当前登录用户
      warehouse: '',
      materialNumber: '',
      materialName: '',
      specification: '',
      unit: '',
      quantity: 0,
      remark: '',
    },
  
    onLoad() {
      // 获取当前登录用户信息
      const currentUser = wx.getStorageSync('currentUser');
      if (currentUser) {
        this.setData({ currentUser });
      } else {
        wx.showToast({
          title: '未登录，请先登录',
          icon: 'none',
          duration: 1500,
        });
  
        setTimeout(() => {
          wx.reLaunch({
            url: '/pages/login/login',
          });
        }, 1500);
      }
    },
  
    onWarehouseInput(e) {
      this.setData({ warehouse: e.detail.value });
    },
  
    onMaterialNumberInput(e) {
      this.setData({ materialNumber: e.detail.value });
    },
  
    onMaterialNameInput(e) {
      this.setData({ materialName: e.detail.value });
    },
  
    onSpecificationInput(e) {
      this.setData({ specification: e.detail.value });
    },
  
    onUnitInput(e) {
      this.setData({ unit: e.detail.value });
    },
  
    onQuantityInput(e) {
      this.setData({ quantity: parseInt(e.detail.value) || 0 });
    },
  
    onRemarkInput(e) {
      this.setData({ remark: e.detail.value });
    },
  
    handleSubmit() {
      const newItem = {
        id: Date.now(),
        warehouse: this.data.warehouse,
        materialNumber: this.data.materialNumber,
        materialName: this.data.materialName,
        specification: this.data.specification,
        unit: this.data.unit,
        quantity: this.data.quantity,
        remark: this.data.remark,
      };
  
      const app = getApp();
      app.globalData.items.push(newItem);
  
      wx.showToast({
        title: '新增成功',
        icon: 'success',
        duration: 1500,
      });
  
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    },
  
    handleSubmit() {
        const { warehouse, materialNumber, materialName, specification, unit, quantity, remark } = this.data;
    
        if (!warehouse || !materialNumber || !materialName || !specification || !unit || quantity <= 0) {
          wx.showToast({
            title: '请填写完整信息',
            icon: 'none',
            duration: 1500,
          });
          return;
        }
    
        const app = getApp();
        const db = app.globalData.db;
    
        // 查询是否有相同物料号的记录
        db.collection('items')
          .where({
            materialNumber,
          })
          .get()
          .then(res => {
            if (res.data.length > 0) {
              // 如果存在相同物料号的记录，更新数量
              const item = res.data[0];
              const newQuantity = item.quantity + quantity;
    
              db.collection('items').doc(item._id).update({
                data: {
                  quantity: newQuantity,
                  updatedAt: new Date(), // 更新时间
                },
                success: () => {
                  wx.showToast({
                    title: '数量更新成功',
                    icon: 'success',
                    duration: 1500,
                  });
    
                  setTimeout(() => {
                    wx.navigateBack(); // 返回上一页
                  }, 1500);
                },
                fail: (err) => {
                  wx.showToast({
                    title: '更新失败，请重试',
                    icon: 'none',
                    duration: 1500,
                  });
                  console.error(err);
                },
              });
            } else {
              // 如果不存在相同物料号的记录，插入新记录
              db.collection('items').add({
                data: {
                  warehouse,
                  materialNumber,
                  materialName,
                  specification,
                  unit,
                  quantity,
                  remark,
                  createdAt: new Date(), // 记录创建时间
                },
                success: () => {
                  wx.showToast({
                    title: '新增成功',
                    icon: 'success',
                    duration: 1500,
                  });
    
                  setTimeout(() => {
                    wx.navigateBack(); // 返回上一页
                  }, 1500);
                },
                fail: (err) => {
                  wx.showToast({
                    title: '新增失败，请重试',
                    icon: 'none',
                    duration: 1500,
                  });
                  console.error(err);
                },
              });
            }
          })
          .catch(err => {
            wx.showToast({
              title: '查询失败，请稍后重试',
              icon: 'none',
              duration: 1500,
            });
            console.error(err);
          });
      },
  });